import { nmAppErrorLog } from '@/common/utils';
import showLoading from '@/components/Loading';
import { basic } from '@/domain';
import { MessageTip, S3Inst, StringUtils } from '@amcax/base';
import { InboxOutlined } from '@ant-design/icons';
import { RJSFSchema } from '@rjsf/utils';
import type { UploadProps } from 'antd';
import { Upload } from 'antd';
import i18n from 'i18next';
import { CmdDialogForm } from 'nextcae-base';

const { Dragger } = Upload;

interface ImportDialogProps {
  title: string;
  onClose: () => void;
}

export function ImportDialog({ title, onClose }: ImportDialogProps) {
  let fileType = '';

  const uploadFile = (options) => {
    const hide = showLoading();
    const { file, onSuccess, onProgress } = options;
    const fileTypeIndex = file.name.split('.').length - 1;
    fileType = file.name.split('.')[fileTypeIndex];
    const ossfile = StringUtils.randomString(10) + '.' + fileType;
    S3Inst.uploadFile(
      'cad',
      ossfile,
      file,
      (progress: { loaded: number; total: number }) => {
        const percentage = Math.floor((progress.loaded * 100) / progress.total);
        onProgress({ percent: percentage }, file);
      },
      async (data: { bucket: string; path: string }) => {
        const bucket = data.bucket;
        const path = data.path;
        try {
          await basic.import('s3://' + bucket + path);
          onClose();
          onSuccess({ name: path, status: 'done', file });
        } catch (error) {
          nmAppErrorLog('import error', error);
        } finally {
          hide();
        }
      },
    );
  };

  // 宽度为400px
  const props: UploadProps = {
    name: 'file',
    multiple: true,
    accept: '.xyz, .stl, .obj, .stp, .step, .iges, .zip',
    onChange(info) {
      if (info.file.status === 'error') {
        MessageTip.error(`${info.file.name} 文件上传失败`);
      }
    },
    customRequest: uploadFile,
  };

  const UploadDragger = () => {
    return (
      <Dragger {...props}>
        <p className='ant-upload-drag-icon'>
          <InboxOutlined />
        </p>
        <p className='ant-upload-text'>{i18n.t('uploader.drag_text')}</p>
        <p className='ant-upload-hint'>支持上传文件类型: {props.accept}</p>
      </Dragger>
    );
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      upload: {
        type: 'string',
      },
    },
  };

  return (
    <CmdDialogForm
      title={title}
      onClose={onClose}
      schema={schema}
      extraUiSchema={{
        upload: {
          'ui:field': UploadDragger,
        },
      }}
      titleIcon='commands/standard/import'
      showSubmit={false}
      showCancel={false}
      footerChildren={<></>}
    />
  );
}
